import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getManager, Repository } from 'typeorm';
import { TreePerson } from '@/modules/tree-person/tree-person.entity';

@Injectable()
export class TreePersonService {
  constructor(
    @InjectRepository(TreePerson)
    private readonly treePersonRepository: Repository<TreePerson>,
  ) {}

  async createTest(body): Promise<object> {
    const { parentId, title } = body;
    console.log(parentId, title);
    const manager = getManager();
    // 获取父级的树
    const parentNode = await manager.findOne(TreePerson, parentId);
    console.log(parentNode);
    // 创建当前节点
    const currentNode = new TreePerson(title);
    // 设置关系
    if (parentNode instanceof TreePerson) {
      currentNode.parent = parentNode;
      // 存储树
      await manager.save(currentNode);
      return { msg: 'create success' };
    }
    //
    // const a1 = new TreePerson('a1');
    // a1.title = 'a1';
    // await manager.save(a1);
    //
    // const a11 = new TreePerson();
    // a11.title = 'a11';
    // a11.parent = a1;
    // await manager.save(a11);
    //
    // const a12 = new TreePerson();
    // a12.title = 'a12';
    // a12.parent = a1;
    // await manager.save(a12);
    //
    // const a111 = new TreePerson();
    // a111.title = 'a111';
    // a111.parent = a11;
    // await manager.save(a111);
    //
    // const a112 = new TreePerson();
    // a112.title = 'a112';
    // a112.parent = a11;
    // await manager.save(a112);
    return { msg: null };
  }

  async getAll(param): Promise<TreePerson[]> {
    console.log(param);
    const manager = getManager();
    const res = await manager.getTreeRepository(TreePerson).findTrees();
    console.log(res);
    return res;
  }
}
